import {Injectable, CanActivate, ExecutionContext, ForbiddenException} from '@nestjs/common';
import { Reflector } from '@nestjs/core';

/**
 * 自定义权限会话验证（守卫）
 * 绑定守卫 @UseGuards(AuthGuard）
 */
@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private readonly reflector: Reflector) {}
    //   获取执行上下文
    canActivate(context: ExecutionContext): boolean {
        const request = context.switchToHttp().getRequest();
        const UserSession: any = request.session.data;
        if(!UserSession) {
            throw new ForbiddenException({
                statusCode: 401,
                error: "未登录"
            });
        }
        /**
         * 获取上下文
         * 判断当前权限点 @SetMetadata('right', '')
         */
        const valid_right = this.reflector.get<string>('right', context.getHandler());
        if(valid_right) {
            return UserSession.Rights.includes(valid_right);
        }
        else {
            return true;
        }
    }
}
